const fs = require('fs');
const { ROLE_TYPE } = require('../utils/constant');
const { getUniqueId } = require('../utils/time');
const { paginateArray, PAGE_SIZE } = require('../utils/page');

/**
 * 查询所有用户并返回
 * @returns 
 */
async function readUser() {
    try {
        const res = await fs.readFileSync(`./data/use.txt`, 'utf-8');

        // const data = eval('(' + res + ')');
        const data = res.toString();
        // 判断是否有数据
        if (data) {
            const arr = JSON.parse(data);
            return Promise.resolve(arr);
        } else {
            return Promise.resolve([]);
        }

    } catch (error) {
        // 判断是否文件不存在
        console.log('错误',);
        if (String(error).indexOf('no such file or directory') !== -1) {
            return Promise.resolve([]);
        }
        return Promise.reject(error);
    }
}

/**
 * 添加用户
 * @param {*} content 用户信息
 * @returns 
 */
async function addUser(content) {
    try {
        const res = await readUser();
        console.log('数据', content);
        const uniqueId = getUniqueId();
        content.id = uniqueId;
        // 默认为游客角色
        if(!content.roleType){
            content.roleType = ROLE_TYPE.游客;
        }
        if (res && Array.isArray(res)) {
            res.unshift(content);
        }
        const data = JSON.stringify(res)
        await fs.writeFileSync(`./data/use.txt`, data);
        return Promise.resolve();
    } catch (error) {
        return Promise.reject();
    }
}

/**
 * 编辑用户
 * @param {*} content 用户信息
 * @returns 
 */
async function updateUser(content) {
    try {
        const res = await readUser();
        const id = content.id;
        let index = -1;
        if (res && Array.isArray(res)) {
           index = res.findIndex((item) => item.id === id);
        }
        if(index < 0){
            throw new Error();
        }
        const data = JSON.parse(JSON.stringify(res));
        data.splice(index, 1);
        data.unshift(content);
        console.log(2,data);
        await fs.writeFileSync(`./data/use.txt`, JSON.stringify(data));
        return Promise.resolve();
    } catch (error) {
        console.log(error);
        return Promise.reject();
    }
}

/**
 * 删除用户
 * @param {*} id 用户id
 * @returns 
 */
async function deleteUser(query) {
    try {
        const res = await readUser();
        const index = res.findIndex((item) => query.id === item.id);
        console.log(index);
        res.splice(index, 1);
        const data = JSON.stringify(res)
        await fs.writeFileSync(`./data/use.txt`, data);
        return Promise.resolve(index);
    } catch (error) {
        return Promise.reject();
    }
}

/**
 * 分页查询用户
 * @param {*} params 查询参数
 * @returns 
 */
async function queryUser(params) {
    const { pageNum, pageSize, searchParams } = params;
    try {
        const res = await readUser();
        const pageResult = paginateArray(res, pageNum, pageSize ? pageSize : PAGE_SIZE, searchParams);
        return Promise.resolve(pageResult);
    } catch (error) {
        console.log(error);
        return Promise.reject(error);

    }

}

/**
 * 用户登录
 * @param {*} data 登录参数
 */
async function userLogin(data) {
    console.log('参数',data);
    try {
        const res = await readUser();
        console.log('数据', res);
        // 返回登录状态
        const resData = {
            code: 200,
            msg: '登录成功'
        }
        // 判断是否存在用户
        const index = res.findIndex((item) => item.username === data.username);
        console.log('index', index);
        if( index < 0 ){
            resData.code = 500;
            resData.msg = '用户不存在';
            return Promise.resolve(resData);
        }else{
            const user = res[index];
            if(user.password !== data.password){
                resData.code = 500;
                resData.msg = '用户或密码不正确';
                return Promise.resolve(resData);
            }
        }
        const { roleType } = data;
        if( roleType && res[index].roleType !== roleType){
            resData.code = 500;
            resData.msg = '登录角色不匹配';
            return Promise.resolve(resData);
        }
        resData.data = res[index];
        return Promise.resolve(resData);
    } catch (error) {
        return Promise.reject(error);
    }
}

/**
 * 用户注册
 * @param {*} data 
 * @returns 
 */
async function userRegister(data) {
    try {
        const res = await readUser();
        // 返回登录状态
        const resData = {
            code: 200,
            msg: '注册成功！'
        }
        // 判断是否存在用户
        const index = res.findIndex((item) => item.username === data.username);
        console.log('index', index);
        if( index > -1 ){
           resData.code = 500;
           resData.msg = '该账号已被注册！';
           return Promise.resolve(resData);
        }
        // 添加用户
        await addUser(data);
        return Promise.resolve(resData);
    }catch (error) {
        return Promise.reject(error);
    }
}

exports.addUser = addUser;
exports.deleteUser = deleteUser;
exports.queryUser = queryUser;
exports.userLogin = userLogin;
exports.userRegister = userRegister;
exports.updateUser = updateUser;